package com.mdnote.practice.array;

import java.util.Arrays;

/**
 * @author Rhythm-2019
 * @date 2020/10/7
 * @description 7颜色分类
 */
public class  LeetCode75 {

    public static void main(String[] args) {
        LeetCode75 leetCode75 = new LeetCode75();
        int[] arr = {0, 1, 0, 1, 0, 1};
        leetCode75.sortColors(arr);
        System.out.println(Arrays.toString(arr));
    }
    public void sortColors(int[] nums) {
        // 计数排序
//        count_sort(nums);
        // 双指针
        double_cursor(nums);
    }

    private void double_cursor(int[] arr) {
        // 定义两个指针，p1 指向0可以插入的位置， p2 指向1可以插入的位置
        int p0 = 0, p1 = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == 0) {
                swap(i, p0, arr);
                // 有一种情况，   0   0   0   1   1   2   2   0
                //                         [0      p1       i
                // 要换两次
                if (p0 < p1) {
                    swap(i, p1, arr);
                }
                p0++;
                // 0放在前面，可以放1的位置要向后走
                p1++;
            } else if (arr[i] == 1) {
                swap(i, p1, arr);
                p1++;
            }
        }
    }

    private void double_cursor2(int[] nums) {
        int p0 = 0, p2 = nums.length - 1;
        for (int i = 0; i < nums.length; i++) {
            while (i <= p2 && nums[i] == 2 ){
                // 换到不是2为止
                swap(i, p2, nums);
                p2--;
            }
            if (nums[i] == 0) {
                swap(i, p0, nums);
                p0++;
            }
        }
    }

    public void swap(int index1, int index2, int[] arr) {
        int temp = arr[index1]; arr[index1] = arr[index2]; arr[index2] = temp;
    }

    private void count_sort(int[] arr) {
        int count_r = 0, count_b = 0, count_w = 0;
        for (int i = 0; i < arr.length; i++) {
            int t = arr[i] == 0 ? count_r++ : arr[i] == 1 ? count_w++ : count_b++;
        }
        int index = 0;
        while (index < arr.length) {
            if (count_r != 0) {
                count_r--;
                arr[index++] = 0;
            } else if (count_w != 0) {
                count_w--;
                arr[index++] = 1;
            } else {
                count_b--;
                arr[index++] = 2;
            }
        }
    }
}
